<?php
namespace app\controller\model\apis\service;

use app\BaseController;
use app\controller\model;
use GuzzleHttp\Client;
use think\facade\Db;
use extend\yeepay;
use yeepay\YopRequest;
use yeepay\YopConfig;
use yeepay\YopRsaClient;

class YeepayModel extends BaseController
{
	public $urlTest="";
	public $develop=true;
	public $apiUrl="";
	protected $url='',$appKey,$secret,$serviceCode,$tables,$token,$iv,$key;
	public $supplier;
	public $data,$method,$appID;
	protected $header=["Content-Type" => "application/json"];
    public function __construct($service=[]){
	    $this->tables = new model\Tables();
		$this->start($service);
    }
	function getAmount($orderNo,$amount,$shopNo){
	    $log = app(\app\Log::class, ['dir' => 'yop/getAmount']);
		//代扣
		$request = new YopRequest($this->appID, $this->secret);
		$request->addParam("parentMerchantNo", $this->serviceCode);
		$request->addParam("merchantNo", $this->serviceCode);
		$request->addParam("payerMerchantNo", $shopNo);
		$request->addParam("orderId", $orderNo);
		$request->addParam("orderAmount", $amount);
		$request->addParam("goodsName", 'Api代扣');
		$request->addParam("payerNotifyUrl", apiURLHTTP().apiURL().'/YeePayNotify/pushPay');
		$request->addParam("fundProcessType","DELAY_SETTLE");
		$response = YopRsaClient::post("/rest/v1.0/account/enterprise/withholding/order", $request);
		$log->write(['request' => $request->paramMap,'header'=>$request->headers, 'response' => json_decode(json_encode($response), true)]);
		return json_decode(json_encode($response),true);
	}
	function getPayMoney($account){
	    $log = app(\app\Log::class, ['dir' => 'yop/getPayMoney']);
		//直接全部提现
		$request = new YopRequest($this->appID, $this->secret);
		//加入请求参数
		$request->addParam("merchantNo", $account);
		$request->addParam("settleRequestNo", getOrderNo());
		$request->addParam("operatePeriod", "ALL");
		$request->addParam("notifyUrl", apiURLHTTP() . apiURL() . '/YeePayNotify/pay');
		//提交Post请求
		$response = YopRsaClient::post("/rest/v1.0/settle/self-settle/apply", $request);
		$log->write(['request' => $request->paramMap,'header'=>$request->headers, 'response' => json_decode(json_encode($response), true)]);
        return json_decode(json_encode($response), true);
	}
	
	function divide($orderNo, $uniqueOrderNo, $orders, $amount, $acccount)
    {
        //分账请求
        $request = new YopRequest($this->appID, $this->secret);
//        dd($request,$orderNo, $uniqueOrderNo, $orders, $amount, $acccount);
        $request->addParam("merchantNo", $this->serviceCode);
        $request->addParam("parentMerchantNo", $this->serviceCode);
        $request->addParam("orderId", $orderNo);
        $request->addParam("uniqueOrderNo", $uniqueOrderNo);
        $request->addParam("divideRequestId", $orders);
        //{"amount":"100.00","ledgerNo":"10000466938","ledgerType":"MERCHANT2MERCHANT","divideDetailDesc":"供应商结算"}
        $request->addParam("divideDetail", json_encode([
            ["amount" => $amount, "ledgerNo" => $acccount, "ledgerType" => "MERCHANT2MERCHANT", "divideDetailDesc" => "供应商结算", "ledgerNoFrom" => $this->serviceCode]
        ], 320));
        $request->addParam("isUnfreezeResidualAmount", "FALSE");
        $response = YopRsaClient::post("/rest/v1.0/divide/apply", $request);
        $log = app(\app\Log::class, ['dir' => 'yop/divide']);
        $log->write(['request' => $request->paramMap,'header'=>$request->headers, 'response' => json_decode(json_encode($response), true)]);
        return (json_decode(json_encode($response), true));
    }
	
	function getBanks(){
		//查询所有结算账户
		$request = new YopRequest($this->appID, $this->secret);
		//加入请求参数
		$request->addParam("merchantNo", $this->serviceCode);
		//提交Post请求
		$response = YopRsaClient::post("/rest/v1.0/settle/settle-way/query", $request);
		var_dump($response);
	}
	function getPayMoney2(){
		$this->method = 'queryYopBalance';
		$this->setData();
		$this->data['data']=json_encode(['ypMerchantNo'=>$this->serviceCode]);
		$this->mkSign();
		//不支持测试环境
		return $this->sendUrl('merchant/queryYopBalance');
	}
	protected function setData(){
		$this->data=[
			'appKey'=>$this->appKey,
			'method'=>$this->method,
		];
	}
	protected function start($service=[]){
		$this->service = $service;
		$this->apiUrl = 'https://api.jches.com/api/supplier/open';
		$this->urlTest = 'https://dev.jches.com/api/supplier/open';
		if(isset($this->service['develop'])){
			if($this->service['develop']==-1) $this->develop=false;
		}
		$this->develop=false;
		!$this->develop?$this->url = $this->apiUrl:$this->url = $this->urlTest;
		$this->url = trim($this->url,"/")."/";
		$this->appKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA6p0XWjscY+gsyqKRhw9MeLsEmhFdBRhT2emOck/F1Omw38ZWhJxh9kDfs5HzFJMrVozgU+SJFDONxs8UB0wMILKRmqfLcfClG9MyCNuJkkfm0HFQv1hRGdOvZPXj3Bckuwa7FrEXBRYUhK7vJ40afumspthmse6bs6mZxNn/mALZ2X07uznOrrc2rk41Y2HftduxZw6T4EmtWuN2x4CZ8gwSyPAW5ZzZJLQ6tZDojBK4GZTAGhnn3bg5bBsBlw2+FLkCQBuDsJVsFPiGh/b6K/+zGTvWyUcu+LUj2MejYQELDO3i2vQXVDk7lVi2/TcUYefvIcssnzsfCfjaorxsuwIDAQAB';
		$this->secret = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDWgePTPGxGhv07CeUk63iIK9R+137QUTuRDKjciakqy6PRCASkYeRAv/8KkfRi8vUfi0LupbMePRF3ZNavRtVHQr71RtDQHsgcjqqvXhGrBnwckpE2X6d6SalKan+xN9C/9GpSO5oNbsxaU9yUzB6VeuVaOO/4puA8IBlYpK/uwDy1WpEllG9PNaeP8WTbGMDtcQEAq59q11dhrEUaQQxQ9Xp/jXvks9/BPPyhIDtNN9sYSGVgPPsv7kFNIPrGz6E5zpUqT+vdkwHccR8cppBue3334dtlEdX2BFW2jF8ZccrESbTcXR5jDMrllaekPR4/H7/bJXA75xj0NI9e552LAgMBAAECggEAIxedz2VvqzwTOnDceWVCUzika1nSx766WXjyOR4WPEeTVbOTmtbe8g7W6QJGsldf7ZipSwR1oKlJ7bfj/Um/w4gyWEsNBzc58p4OY2Emz81gSYZa1kPg0LszRFbW7AWfE4AnUquogLETImXczMT17etskQ2GiK24Om3f56YNmCezI0L9gcnCOluGievBPWEQRwbtJ63NRgvhxNuVuffg9ejjHpEPLamH/qjqaw58GImBAomKTVZPIjAKRGkfR+o24X8ObCYdJDTVXGQo+ZF07lBEePYELyD5MFbto0Q3jhNGtlS0o1uJF669XlNEpYI4NS3xwFpmAdMbmjlIBopV9QKBgQDfPuefIGki3uAUIUiOj3p6z4L4TTGTud8duAwg20LA3dizNpeYgXBwHhIAivpwfhJSGPzIDMHchvO+yqe/zn/ppyB8OT+79tEWsvcWYt04f+8U61SeOJ0nwuxWshnbRd/M4I6g7RThDtVrToogLmkHsa/2gc8N/O0C+Sz46MBAZQKBgQD1+sYRUQ6Akm/X5s2IWEoyxjAfM+/6AHooYbXzki3fMfqY88k7XsHvHQ0vHOUwTIYR3FZ+lklukL0uoUowBXfGq5j0wDKTS3XeMPlBW2za3kV545Qfw+3o3tcM8fIns3WbVWmPyNXtq1MU7J4sBxO3P7NcXbcgNUetPzzgNfBvLwKBgQCVCKKKCZIGdHF1Hs8YVNJ4QCX361iofRJk/aQjHx0OMkvjQBOt/ON6BakQ8bbE+HT0l7fROSsGNJVuDk40bv/XlPnL1FAnBFuLYsgvCqsSd928wmnIApVvoOIz8kvupVQFqvesmPkyUbvKGjF90F3PhCCrWPdIKEx1irEqLf+CPQKBgDF7wVy6cbBrxRQp2i8Tk9mjBQtB54Tjk6+L+I6HWbMM2tzqLhFDfsAbmAtiRLjyrAXrzXqpwRv9AhHfYI1IjE/rNVoHUCVRiOSp9XqwabWeAVwD7Eh3oeS274wrIAvcjkwxYosKW/7z+EK9VxSEV/MFXY+3Sp+wGDtB/X0dXMEBAoGAUI6y/dE6tBbngGt79+FjtVw+XKpL+/QE7M58ba3IN4afx0uEW2POcw10hmPamAQ9wYDXC6m9HdcxBMrgoX33Ft2FPEzRsEatPSDL3/f7w8ry1pytgjg34FZCHvDWSFaDORaqXf/DgL/VN2HMHdJbDYQz6rKMgt/uIRgjwgBklOU=';
		$this->key = substr($this->secret,0,16);
		$this->iv = substr($this->secret,-16);
		$this->serviceCode = '10091476287';
		$this->appID = 'app_10091476287';
	}
	protected function mkSign(){
		$this->data['timeStamp'] = "".time();
		$this->data['data']=$this->aesEncrypt($this->data['data']);
		$str = strtoupper($this->data['data'].$this->data['method'].$this->data['timeStamp']);
		$this->data['sign'] = md5($this->secret.$this->appKey.$str);
	}
	function aesEncrypt($plaintext){
		$cipher_algo = 'AES-2048-CBC';
		$ciphertext = openssl_encrypt($plaintext, $cipher_algo, $this->key, 0, $this->iv);
		if ($ciphertext === false) {
			return false;
		}
		return $ciphertext;
	}
	protected function sendUrl($pra=''){
		if($pra=='') return [];
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => $this->url.$pra,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS =>json_encode($this->data),
			CURLOPT_HTTPHEADER => array(
				'Content-Type: application/json'
			),
		));
		$response = curl_exec($curl);
		curl_close($curl);
		var_dump($this->data);
		return json_decode($response,true);
	}
}
?>